7 SegmentTree(const vector
<int> &arr
) : arr(arr
) {
11 //must be called after assigning a new arr.
15 initialize(0, 0, n
-1);
18 int query(int query_left
, int query_right
) const{
19 return query(0, 0, n
-1, query_left
, query_right
);
22 void update(int where
, int what
){
23 update(0, 0, n
-1, where
, what
);
27 int initialize(int node
, int node_left
, int node_right
);
28 int query(int node
, int node_left
, int node_right
,
29 int query_left
, int query_right
) const;
30 void update(int node
, int node_left
, int node_right
,
34 int SegmentTree::initialize(int node
,
35 int node_left
, int node_right
){
36 if (node_left
== node_right
){
37 tree
[node
] = node_left
;
40 int half
= (node_left
+ node_right
) / 2;
41 int ans_left
= initialize(2*node
+1, node_left
, half
);
42 int ans_right
= initialize(2*node
+2, half
+1, node_right
);
44 if (arr
[ans_left
] <= arr
[ans_right
]){
45 tree
[node
] = ans_left
;
47 tree
[node
] = ans_right
;
52 int SegmentTree::query(int node
, int node_left
, int node_right
,
53 int query_left
, int query_right
) const{
54 if (node_right
< query_left
|| query_right
< node_left
)
56 if (query_left
<= node_left
&& node_right
<= query_right
)
59 int half
= (node_left
+ node_right
) / 2;
60 int ans_left
= query(2*node
+1, node_left
, half
,
61 query_left
, query_right
);
62 int ans_right
= query(2*node
+2, half
+1, node_right
,
63 query_left
, query_right
);
65 if (ans_left
== -1) return ans_right
;
66 if (ans_right
== -1) return ans_left
;
68 return (arr
[ans_left
] <= arr
[ans_right
] ? ans_left
: ans_right
);
71 void SegmentTree::update(int node
, int node_left
, int node_right
,
73 if (where
< node_left
|| node_right
< where
) return;
74 if (node_left
== where
&& where
== node_right
){
79 int half
= (node_left
+ node_right
) / 2;
81 update(2*node
+1, node_left
, half
, where
, what
);
83 update(2*node
+2, half
+1, node_right
, where
, what
);
85 if (arr
[tree
[2*node
+1]] <= arr
[tree
[2*node
+2]]){
86 tree
[node
] = tree
[2*node
+1];
88 tree
[node
] = tree
[2*node
+2];